var dataSource = new Array();
//table的数据源
var table;   //table对象;
var pageNum = 1;
var pageSize;
dataSource = [];
function searchList(pageNum){
    $.ajax({
        url: root.couponInter.coupon_getCouponTopicList,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "topicType":$('#topicType').val(),
            "topicCode":$('#topicCode').val(),
            "topicStatus":$('#topicStatus').val(),
            "topicName":$('#topicName').val(),
            "createUsername":$('#createUsername').val(),
            "createDept":$('#createDept').val(),
            "amountStartValue":$('#amountStartValue').val(),
            "amountEndValue":$('#amountEndValue').val(),
            "createStartTimeValue":$('#createStartTimeValue').val(),
            "createEndTimeValue":$('#createEndTimeValue').val(),
            "activeStartTimeValue":$('#logmin').val(),
            "activeEndTimeValue":$('#logmax').val(),
            "topicUseTag":$('#isLotteryDrawUse').val(),
            "pageNum":pageNum,
            "pageSize":10,
        }),
        success: function (result) {
            console.log(result);
            topiclist(result.result);
            $('.M-box3').pagination({
                pageCount: result.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.couponInter.coupon_getCouponTopicList,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            "topicType":$('#topicType').val(),
                            "topicCode":$('#topicCode').val(),
                            "topicStatus":$('#topicStatus').val(),
                            "topicName":$('#topicName').val(),
                            "createUsername":$('#createUsername').val(),
                            "createDept":$('#createDept').val(),
                            "amountStartValue":$('#amountStartValue').val(),
                            "amountEndValue":$('#amountEndValue').val(),
                            "createStartTimeValue":$('#createStartTimeValue').val(),
                            "createEndTimeValue":$('#createEndTimeValue').val(),
                            "activeStartTimeValue":$('#logmin').val(),
                            "activeEndTimeValue":$('#logmax').val(),
                            "topicUseTag":$('#isLotteryDrawUse').val(),
                            "pageNum":api.getCurrent(),
                            "pageSize":10,
                        }),
                        success: function (result) {
                            topiclist(result.result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
function topiclist(data) {
    console.log(data)
    dataSource.splice(0,dataSource.length);//清空数组
    $.each(data, function (i, field) {
        var rowData = new Array();
        rowData.push(field.topicType);
        rowData.push(field.topicCode);
        rowData.push(field.topicName);
        rowData.push(field.topicUseTag);//是否抽奖使用
        rowData.push(field.amount);
        rowData.push(field.totalCount);
        rowData.push(field.createDept);
        rowData.push(field.createUsername);
        rowData.push(field.createdAt);
        rowData.push(field.createdAt);
        rowData.push(field.topicStatus);
        rowData.push(field.useBegtime);
        rowData.push(field.useEndtime);
        rowData.push(field.topicId);
        rowData.push(field.dayNumber);
        dataSource.push(rowData);
    });
    initDataTable(dataSource);
    function initDataTable(dataSource) {
        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "order": [[ 7, "desc" ]],
            "autoWidth": false,
            "ordering": true,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [20],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if(row[0]==10){
                            val='满减券';
                            return val;
                        }else if(row[0]==20){
                            val='运费券';
                            return val;
                        }
                        return val;
                    },
                    "targets":0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if(row[3]==20){
                            val='是'
                        }
                        else if(row[3]==10){
                            val='否'
                        }
                        return val;
                    },
                    "targets":3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if(row[14]>0){
                            val='领到券当日开始'+row[14]+'天内有效'
                        }else{
                            val = row[11]
                        }
                        return val;
                    },
                    "targets":9
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if(row[10]==10){
                            val='已生效'
                        }
                        else if(row[10]==40){
                            val='强制失效'
                        }
                        else if(row[10]==30){
                            val='已失效'
                        }
                        return val;
                    },
                    "targets":10
                },
                {
                    "render": function (data, type, row, meta) {
                        var val='';
                        if(row[10]==10){
                            val = '<div class="action" id="action'+row[13]+'"><a class="powerButton 152" style="margin-right: 20px"><span class="list" id="'+row[13]+'" onclick="confirm(id)">强制失效</span></a>' +
                                '<a class="powerButton 151"><span class="list"  onclick="detail(\'电子券详情\',\'coupon-topic-detail.html\',\''+row[13]+'\')">查看</span></a></div>' +
                 '<div id="confirm'+row[13]+'" class="hide"><textarea style="width:250px;height:200px;resize: none;" maxlength="200" placeholder="请输入失效原因(200字以内)" id="reason'+row[13]+'" ></textarea><br><div class="btn btn-primary btn-primary wd-100 radius" onclick="finish(id)" id="'+row[13]+'">提交</div></div>';
                        }
                        else if(row[10]==40){
                            val='<div class="action" id="action'+row[13]+'"><a class="powerButton 152" style="margin-right: 20px;color:#999"><span class="list" id="'+row[13]+'">强制失效</span></a>' +
                                '<a class="powerButton 151"><span class="list" onclick="detail(\'电子券详情\',\'coupon-topic-detail.html\',\''+row[13]+'\')">查看</span></a></div>'
                        }
                        else if(row[10]==30){
                            val='<div class="action" id="action'+row[13]+'"><a class="powerButton 152" style="margin-right: 20px;color:#999"><span class="list" id="'+row[13]+'">强制失效</span></a>' +
                                '<a class="powerButton 151"><span class="list" onclick="detail(\'电子券详情\',\'coupon-topic-detail.html\',\''+row[13]+'\')">查看</span></a></div>'
                        }
                        return val;
                    },
                    "targets":11
                }
            ]
        });
        //权限控制函数
        power()
    };
}
function testclick(){
    console.log(1)
}
// function getList(pagenum){
//     $("#area").val()
//     $.ajax({
//         contentType: "application/json",
//         type: "post",
//         url: root.orderInter.order_queryMaintainOrder,
//         cache: false,  //禁用缓存
// //        dataType: "json",
//         data: JSON.stringify({
// //          "created_address_code": $("#area").val(),//地区
//             "warehouse_id": 1,// 仓库id
//             "maintain_id": $("#applyCode").val(),//维修申请单号
//             "order_id":$("#orderCode").val(),//订单号
//             "maintain_type":$("#mainType").val(),//送修方式
//             "maintain_status":$("#dealState").val(),//状态
//             "maintain_reason":$("#maintainReason").val(),//维修原因
//             "customer_name":$("#buyerName").val(),//客户名称
// //          "audit_person_name":$("#checker").val(),//审核人
//             "sales_manager_name":$("#saleManager").val(),//销售经理
//             "page_num":pagenum,
//             "page_size":5
//         }),
//         success: function (result) {
//             console.log(result)
//             orderList(result);
//             $('.M-box3').pagination({
//                 pageCount: result.totalPage,
//                 jump: true,
//                 coping: true,
//                 prevContent: '上页',
//                 nextContent: '下页',
//                 callback: function (api) {
//                     $.ajax({
//                         contentType: "application/json",
//                         type: "POST",
//                         url: root.orderInter.order_queryMaintainOrder,
//                         cache: false,  //禁用缓存
//                         dataType: "json",
//                         data: JSON.stringify({
// //          "created_address_code": $("#area").val(),//地区
//                             "warehouse_id": 1,// 仓库id
//                             "maintain_id": $("#applyCode").val(),//维修申请单号
//                             "order_id":$("#orderCode").val(),//订单号
//                             "maintain_type":$("#mainType").val(),//送修方式
//                             "maintain_status":$("#dealState").val(),//状态
//                             "maintain_reason":$("#maintainReason").val(),//维修原因
//                             "customer_name":$("#buyerName").val(),//客户名称
// //          "audit_person_name":$("#checker").val(),//审核人
//                             "sales_manager_name":$("#saleManager").val(),//销售经理
//                             "page_num":api.getCurrent(),
//                             "page_size":5
//                         }),
//                         success: function (result) {
//
//                             orderList(result);
//                         },
//                         error: function (XMLHttpRequest, textStatus, errorThrown) {
//                             alert(XMLHttpRequest);
//                         }
//                     });
//                 }
//             });
//         },
//         error: function (XMLHttpRequest, textStatus, errorThrown) {
//             console.log( "响应吗 = "+ XMLHttpRequest.status);
//             console.log( "readyState = "+ XMLHttpRequest.readyState);
//         }
//     });
// }
var index=0;
function confirm(id) {
    index = layer.open({
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        title: '<span style="position:relative;left: 25px;">失效原因</span>',
        shadeClose:false,
        content:$('#confirm'+id+''),
    });
    $('#confirm'+id+'').removeClass('hide');
}
function finish(id){
    var target = document.getElementById(''+id+'');
    var reason=$('#reason'+id+'').val();
    console.log(target.parentElement.parentElement.parentElement.previousElementSibling)
    if(reason!=''){$.ajax({
        url: root.couponInter.coupon_topicForceInvalid,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        // contentType: "application/json",
        data: {
            "topicId":id,
            "reason":reason,
        },
        success: function () {
            /*$.ajax({
                url: root.couponInter.coupon_getCouponTopicList,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                contentType: "application/json",
                data: JSON.stringify({
                    "topicType":$('#topicType').val(),
                    "topicCode":$('#topicCode').val(),
                    "topicStatus":$('#topicStatus').val(),
                    "topicName":$('#topicName').val(),
                    "createUsername":$('#createUsername').val(),
                    "createDept":$('#createDept').val(),
                    "amountStartValue":$('#amountStartValue').val(),
                    "amountEndValue":$('#amountEndValue').val(),
                    "createStartTimeValue":$('#createStartTimeValue').val(),
                    "createEndTimeValue":$('#createEndTimeValue').val(),
                    "activeStartTimeValue":$('#logmin').val(),
                    "activeEndTimeValue":$('#logmax').val(),

                }),
                success: function (data) {
                    console.log(data);
                    topiclist(data);
                },
                error: function () {
                    $.Huimodalalert('失败！',2000);
                }
            });*/
            target.style.color='#999';
            target.onclick = null;
            target.parentElement.parentElement.parentElement.previousElementSibling.innerHTML='强制失效'
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })}
    else{
        $.Huimodalalert('失效原因不能为空！',2000);
    };
   layer.close(index);
}
function detail(title,url,topicId) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url +'?topicId='+topicId
    });
    layer.full(index);
}
var flag1 = true;
$('#createDept').on('compositionstart',function(){
    flag1 = false;
})
$('#createDept').on('compositionend',function(){
    flag1 = true;
})
$('#createDept').on('input',function(){
    var _this = this;
    setTimeout(function(){
        if(flag1){
            var value=$(_this).val();
            $('li').remove();
            $.ajax({
                url: root.accessInter.access_department_listDepartment,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                data:{
                    "keywords":value
                },
                success: function (data) {
                    console.log(data);
                    if(value!='')
                    {
                        $(".deptlist").removeClass('hide');
                        for (var i in data.bianmaList) {
                            $("#deptList").append('<li id="'+data.bianmaList[i].BIANMA+'" class="depts">' + data.bianmaList[i].DEPARTMENT_NAME + '</li>');
                        }
                    }
                    else{
                        document.getElementsByClassName('deptlist')[0].classList.add('hide');
                    }
                    $('.depts').on('click',function () {
                        $('#createDept').val(this.innerHTML);
                    })
                }
            });
        }
    },0)
})

var flag2 = true;
$('#createUsername').on('compositionstart',function(){
    flag2 = false;
})
$('#createUsername').on('compositionend',function(){
    flag2 = true;
})
$('#createUsername').on('input',function(){
    var _this = this;
    setTimeout(function(){
        if(flag2){
            var value=$(_this).val();
            $('li').remove();
            $.ajax({
                url: root.accessInter.access_listUsername,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                data:{
                    "keywords":value
                },
                success: function (data) {
                    console.log(data.userName);
                    if(value!='')
                    {
                        $(".userlist").removeClass('hide');
                        for (var i in data.userName) {
                            $("#userList").append('<li id="'+data.userName[i].USER_ID+'" class="users">'+data.userName[i].NAME+'</li>');
                        }
                    }
                    else{
                        document.getElementsByClassName('userlist')[0].classList.add('hide');
                    }
                    $('.users').on('click',function () {
                        $('#createUsername').val(this.innerHTML);
                    })
                }
            });
        }
    },0)
})
$(document).click(function(e) {
    var target = $(e.target);
    if(target[0].id!='createDept'){
        $('.depts').remove();
        $('.deptlist').addClass('hide');
    }
    if(target[0].id!='createUsername'){
        $('.users').remove();
        $('.userlist').addClass('hide');
    }

})